package com.heima.common.exception;

import com.heima.common.dtos.ResponseResult;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

@RestControllerAdvice
public class BaseCatch {

    @ExceptionHandler(RuntimeException.class)
    public ResponseResult runTimeExceptionHandler(RuntimeException e){

        return ResponseResult.error(500,e.getMessage());
    }

    @ExceptionHandler(LeadException.class)
    public ResponseResult leadExceptionHandler(LeadException e){

        return ResponseResult.error(e.getStatus(),e.getMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseResult method(MethodArgumentNotValidException m){
        BindingResult bindingResult = m.getBindingResult();
        List<ObjectError> allErrors = bindingResult.getAllErrors();
        String msg="";
        for (ObjectError allError : allErrors) {
            String defaultMessage = allError.getDefaultMessage();
            if(msg.length()>0){
                msg+=",";
            }
            msg+=defaultMessage;
        }
        return ResponseResult.error(400, msg);
    }

}
